from flask import Blueprint,request,make_response,jsonify,redirect
import json, random, time, requests
from utils.myredis import r
from models.models import *

left_blue = Blueprint("leftblue",__name__)

# @left_blue.route("/getkind")
# # 获取顶级父类
# def getkind():
#     kinds = db.session.execute("select b.*,a.name as pname,a.id as pid from kind as a left join kind as b on a.id=b.type where a.type=0")
#     kind_lst = []
#     idss = []
#     kinds = list(kinds)
#     if kinds:
#         for i in kinds:
#             # 判断父类是否存在，不存在添加
#             if i.pname not in idss:
#                 idss.append(i.pname)
#                 kind_lst.append({
#                     "id":i.pid,
#                     "name":i.pname,
#                     "son":[{
#                         "name":i.name,
#                         "id":i.id,
#                         "type":i.type
#                     }]
#                 })
#             else:
#                 # 存在，查找父类，遍历父类用子类的pid对比
#                 for (index,p) in enumerate(kind_lst):
#                     if i.pid == p["son"][0]["type"]:
#                         # 将子类加到父类下
#                         kind_lst[index]['son'].append({"id": i.id, "name": i.name})
#     return jsonify({"code": 200, "msg": "获取成功","data":kind_lst})

@left_blue.route("/getkind")
# 页面分类
def getkind():
    kind = Kind.query.all()
    kind_list = []
    reslist = []
    # 读取列表中的每一个放到字典
    dict = {}
    for i in kind:
        reslist.append({
            "value":i.id,
            "label":i.name,
            "type":i.type
        })
    for s in reslist:
        k = s["value"]
        dict[k] = s
    # 判断子类属于那个父类，放到父类的son中
    for j in reslist:
        type = j["type"]
        if type == 0:
            kind_list.append(j)
        else:
            if  "children" not in dict[type]:
                dict[type]["children"] = []
            dict[type]["children"].append(j)
    return jsonify({"code":200,"msg":"获取成功","data":kind_list})







